package eu.jba.denshijisho.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import eu.jba.denshijisho.R;
import eu.jba.denshijisho.entity.CardNote;

public class CardNoteDao extends AbstractDao<CardNote>{
	
	public static final String KEY_ROWID = "_id";
	public static final String KEY_ROW_ID_NAME = "id";
	public static final String KEY_CARD_ID = "card_id";
	public static final String KEY_CARD_NAME = "Card";
	public static final String KEY_NOTE_ID = "note_id";
	public static final String KEY_NOTE_NAME = "Note";

	public CardNoteDao(Context ctx) {
		super(ctx);
	}

	@Override
	protected int getCreateResource() {
		return R.raw.create_table_card_note;
	}

	@Override
	protected int getUpdateResource() {
		return R.raw.update_table_card_note;
	}

	@Override
	protected String getTableName() {
		return getContext().getResources().getString(R.database.CARD_NOTE_TABLE); 
	}

	@Override
	protected ContentValues getInitialValues(CardNote object) {
		final ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_CARD_ID, object.getCardId());
		initialValues.put(KEY_NOTE_ID, object.getNoteId());
		return initialValues;
	}

	@Override
	protected String getRowIdColumnName() {
		return KEY_ROWID;
	}

	@Override
	protected String[] getColumns() {
		return new String[] { KEY_ROWID, KEY_CARD_ID, KEY_NOTE_ID };
	}

	@Override
	protected CardNote convertTo(Cursor cursor) {
		final CardNote cardNote = new CardNote(cursor.getInt(0), cursor.getInt(1), cursor.getInt(2));
		return cardNote;
	}
	
	public List<CardNote> getAll(Integer id) {
		Cursor cursor = null;
		try {
			cursor = getDb().query(
				getTableName(), getColumns(), 
				KEY_CARD_ID + " = ?", new String[] { id.toString() }, null,
					null, null);
			final List<CardNote> list = new ArrayList<CardNote>();
			while (cursor.moveToNext()) {
				list.add(convertTo(cursor));
			}
			return list;
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}
	}	
}
